package com.example.demo.identity;


import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.persistence.*;
import lombok.*;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.List;

@Entity
@Table(name = "common")
@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class User {

    @Id
    @Column(name = "uu_id")
    private String uu_id;

    @Column(name = "username")
    private String username;

    @JsonIgnore
    @Column(name = "password")
    private String password;

    @Column(name = "gex")
    private String gex;

    @Lob
    @Column(name = "TypeOfFriendShips")
    @Convert(converter = TypeOfFriendShipsConverter.class)
    private List<String> TypeOfFriendShips;       // 这是一个JSON数据类型

    @Lob        // 使用这个注解可以存储大文本字段
    @Column(name = "avatar")
    private String avatar;

    @Column(name = "birthday")
    private String birthday;

    @Lob
    @Column(name = "token")
    private String token;

    @Column(name = "country")
    private String country;

    @Column(name = "province")
    private String province;

    @Column(name = "city")
    private String city;

    @Column(name = "SignatureOfTheIndividual", length = 20)
    private String SignatureOfTheIndividual;


    public static class TypeOfFriendShipsConverter implements AttributeConverter<List<String>, String> {
        private final ObjectMapper objectMapper = new ObjectMapper();

        @Override
        public String convertToDatabaseColumn(List<String> attribute) {
            try {
                return objectMapper.writeValueAsString(attribute);
            } catch (JsonProcessingException e) {
                throw new IllegalArgumentException("Error converting JSON", e);
            }
        }

        @Override
        public List<String> convertToEntityAttribute(String dbData) {
            try {
                return objectMapper.readValue(dbData, new TypeReference<List<String>>() {
                });
            } catch (IOException e) {
                throw new IllegalArgumentException("Error converting JSON", e);
            }
        }
    }

}
